const mongoose = Require('mongoose');
const Schema = mongoose.Schema;
const ContentSchema = new Schema({
    title: { type: String, required: true },
    parentId: { type: String, default: null },
    description: String,
    type: { type: String, enum: ['main', 'subset'], required: true },
    images: { type: [], },
    time: { type: Number, },
    interface: { type: [], },
    disable: { type: Boolean, default: false }
}, { timestamps: true });
var formatDoc = function (doc) {
    var data = doc.toJSON({ getters: true });
    data.id = doc._id.toString();
    delete data.createdAt;
    delete data.updatedAt;
    delete data.disable;
    delete data._id;
    return data;
};
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};

var Note_Content = function (options) {
    this.options = options;
    var username = this.options.username;
    var password = this.options.password;
    var ip = this.options.ip;
    var port = this.options.port;
    var DBName = this.options.DBName;
    var PorjectName = 'Note';
    this.module = null;
    this.DBMessage = { message: 'HODE ON' };
    var DBURL = 'mongodb://';
    if (username && password) {
        DBURL = DBURL + username + ':' + password + '@';
    };
    DBURL = DBURL + ip + ':' + (port ? port : '80') + '/' + DBName;
    mongoose.connect(DBURL, { config: { autoIndex: false } });
    this.openEvent = function () { };
    mongoose.connection.on("error", (error) => {
        alert(error.message);
        this.openEvent('数据库连接错误');
        this.DBMessage = error.message;
    });
    mongoose.connection.on("open", () => {
        this.openEvent();
        this.DBMessage.message = false;
        this.module = mongoose.model(PorjectName, ContentSchema, PorjectName);
    });
};
Note_Content.prototype.onOpen = function (event) {
    this.openEvent = event;
};
Note_Content.prototype.creat = function (doc, cb) {
    if (this.DBMessage.message) {
        cb(this.DBMessage.message.message, null);
    } else {
        var data = new this.module(doc);
        // 将单行数据插入到数据库
        data.save(function (err, doc) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDoc(doc));
            };
        });
    };
};
Note_Content.prototype.upDate = function (id, _doc, cb) {
    if (this.DBMessage.message) {
        cb(this.DBMessage.message, null);
    } else {
        this.module.findById(id, function (err, doc) {
            doc.title = _doc.title;
            doc.parentId = _doc.parentId;
            doc.description = _doc.description;
            doc.type = _doc.type;
            doc.images = _doc.images;
            doc.time = _doc.time;
            doc.interface = _doc.interface;
            doc.subset = _doc.subset;
            doc.disable = false;
            doc.save(function (err, doc) {
                if (err) {
                    cb(err.message, null);
                } else {
                    cb(false, formatDoc(doc));
                };
            })
        });
    };
};
Note_Content.prototype.getAll = function (id, cb) {
    if (id) {
        var query = { type: 'subset', parentId: id, disable: false, };
    } else {
        var query = { type: 'main', disable: false, };
    };
    if (this.DBMessage.message) {
        cb(this.DBMessage.message, null);
    } else {
        this.module.find(query).sort("time").exec((err, docs) => {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDocs(docs));
            };
        });
    };
};
Note_Content.prototype.delete = function (id, cb) {
    if (this.DBMessage.message) {
        cb(this.DBMessage.message, null);
    } else {
        // 删除单条记录
        this.module.findById(id, function (err, doc) {
            doc.disable = true;
            doc.save(function (err, doc) {
                if (err) {
                    cb(err.message, null);
                } else {
                    cb(false, formatDoc(doc));
                };
            })
        });
    };
};

const ImageSchema = new Schema({
    base64: { type: String, required: true }
}, { timestamps: true });

var Note_Images = function (options) {
    this.options = options;
    var username = this.options.username;
    var password = this.options.password;
    var ip = this.options.ip;
    var port = this.options.port;
    var DBName = this.options.DBName;
    var PorjectName = 'Image';
    this.module = null;
    this.DBMessage = { message: 'HODE ON' };
    var DBURL = 'mongodb://';
    if (username && password) {
        DBURL = DBURL + username + ':' + password + '@';
    };
    DBURL = DBURL + ip + ':' + (port ? port : '80') + '/' + DBName;
    mongoose.connect(DBURL, { config: { autoIndex: false } });
    this.openEvent = function () { };
    mongoose.connection.on("error", (error) => {
        alert(error.message);
        this.openEvent('数据库连接错误');
        this.DBMessage = error.message;
    });
    mongoose.connection.on("open", () => {
        this.openEvent();
        this.DBMessage.message = false;
        this.module = mongoose.model(PorjectName, ImageSchema, PorjectName);
    });
};

Note_Images.prototype.onOpen = function (event) {
    this.openEvent = event;
};
Note_Images.prototype.creat = function (doc, cb) {
    if (this.DBMessage.message) {
        cb(this.DBMessage.message.message, null);
    } else {
        var data = new this.module({ base64: doc });
        // 将单行数据插入到数据库
        data.save(function (err, doc) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDoc(doc));
            };
        });
    };
};
Note_Images.prototype.creatByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var data = [];
    var CreatEvent = () => {
        this.creat(_array[index].data, (error, doc) => {
            if (error) {
                cb(error, null);
            } else {
                var _data = {
                    title: _array[index].title,
                    id: doc.id,
                };
                data.push(_data);
                if (index >= _array.length - 1) {
                    cb(false, data);
                } else {
                    index++;
                    CreatEvent();
                }
            };
        });
    };
    CreatEvent();
};
Note_Images.prototype.delete = function (id, cb) {
    this.module.findByIdAndRemove({ _id: id }, function (err, numRemoved) {
        if (err) {
            cb(err);
        } else {
            cb(false);
        };
    });
};
Note_Images.prototype.deleteByArray = function (_array, cb) {
    if (_array.length == 0) {
        cb(false, []);
        return;
    };
    var index = 0;
    var deleteEvent = () => {
        this.delete(_array[index], (error) => {
            if (error) {
                cb(error, null);
            } else {
                if (index >= _array.length - 1) {
                    cb(false, []);
                } else {
                    index++;
                    deleteEvent();
                }
            };
        });
    };
    deleteEvent();
};
Note_Images.prototype.get = function (id, cb) {
    this.module.findById(id, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            if (doc) {
                cb(false, formatDoc(doc));
            } else {
                cb('获取图片失败,已经删除');
            };
        };
    });
};


module.exports = {
    Content: function (options) {
        return new Note_Content(options);
    },
    Image: function (options) {
        return new Note_Images(options);
    }
};


